package com.saiyaemon.blog.controller.manager;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.runner.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleConstraint.Initially;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.fabric.xmlrpc.base.Array;
import com.saiyaemon.blog.pojo.Article;
import com.saiyaemon.blog.pojo.ArticleTag;
import com.saiyaemon.blog.pojo.Category;
import com.saiyaemon.blog.pojo.Tag;
import com.saiyaemon.blog.service.ArticleService;
import com.saiyaemon.blog.service.ArticleTagService;
import com.saiyaemon.blog.service.CategoryService;
import com.saiyaemon.blog.service.TagService;
import com.saiyaemon.blog.utils.TimeUtil;

/**
 * @author 作者 SaiyaEmon
 * @date 创建时间：2017年11月30日 上午10:53:57
 */
@Controller
public class ManagerArticleController {

	private static final Logger LOGGER = LoggerFactory.getLogger(ManagerArticleController.class);

	@Autowired
	ArticleService articleService;

	@Autowired
	CategoryService categoryService;

	@Autowired
	ArticleTagService articleTagService;

	@Autowired
	TagService tagService;

	/**
	 * 进入首页
	 * @param pageNum
	 * @param pageSize
	 * @param title
	 * @return
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView showIndex(Integer pageNum, Integer pageSize, String title) {
		ModelAndView modelAndView = new ModelAndView("/manager/index");
		if (pageNum == null || pageNum <= 0)
			pageNum = 1;
		if (pageSize == null || pageSize <= 0)
			pageSize = 5;
		if (title == null)
			title = "";
		PageHelper.startPage(pageNum, pageSize);
		Article article = new Article();
		article.setTitle(title);
		List<Article> list = articleService.selectByExample(article);
		PageInfo<Article> pageInfo = new PageInfo<>(list);
		List<Object> articleInformations = articleService.selectAllInformation(list);

		modelAndView.addObject("articleInformations", articleInformations);
		modelAndView.addObject("pageInfo", pageInfo);
		return modelAndView;
	}
	
	/**
	 * 阅读博客
	 * @param articleId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/article/read/{articleId}", method = RequestMethod.GET)
	public ModelAndView showArticleRead(@PathVariable("articleId") Integer articleId, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("/manager/article-read");
		Article article = new Article();
		int count = articleService.selectCount(article);
		article = articleService.selectById(articleId);
		Map<String, Object> articleInformation = articleService.selectInformation(article);
		System.err.println(articleId);
		if (articleId > 1) {
			Article precArticle = new Article();
			precArticle = articleService.selectById(articleId - 1);
			modelAndView.addObject("prevArticle", precArticle);
		}

		if (articleId < count) {
			Article nextArticle = new Article();
			nextArticle = articleService.selectById(articleId + 1);
			modelAndView.addObject("nextArticle", nextArticle);
		}

		modelAndView.addObject("url", request.getRequestURL());
		modelAndView.addObject("articleInformation", articleInformation);
		return modelAndView;
	}

	/**
	 * 博客编辑页面
	 * @param articleId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/manager/article/{articleId}", method = RequestMethod.GET)
	public ModelAndView showArticleWrite(@PathVariable("articleId") Integer articleId) {
		ModelAndView modelAndView = new ModelAndView("/manager/article");
		modelAndView.addObject("categories", categoryService.selectAll());
		if(articleId ==0)
			return modelAndView;
		Article article = new Article();
		article = articleService.selectById(articleId);
		Map<String, Object> articleInformation = articleService.selectInformation(article);

		StringBuilder stringBuilder = new StringBuilder();
		List<Tag> tags = (List<Tag>) articleInformation.get("tags");
		for (Tag tag : tags) {
			stringBuilder.append(tag.getName() + ",");
		}
		System.out.println("stringBuilder" + stringBuilder);
		String substring = stringBuilder.substring(0, stringBuilder.length() - 1);

		modelAndView.addObject("tags", substring);
		
		modelAndView.addObject("articleInformation", articleInformation);
		return modelAndView;
	}

	

	@RequestMapping(value = "/manager/article/save", method = RequestMethod.POST)
	public ModelAndView saveArticle(Article article, String tags) {
		ModelAndView modelAndView = new ModelAndView("redirect:/");

		article.setUpdateTime(System.currentTimeMillis());
		if (article.getId() != null && article.getId() != 0) {
			articleService.update(article);
		} else {
			article.setCreateTime(System.currentTimeMillis());
			articleService.insert(article);
		}

		ArticleTag articleTag = new ArticleTag();
		articleTag.setArticleId(article.getId());
		List<ArticleTag> articleTags = articleTagService.select(articleTag);
		List<String> oldTagList = new ArrayList<>();

		tags.replaceAll("，", ",");
		String[] tagArray = tags.split(",");
		List<String> newTagList = Arrays.asList(tagArray);
		List<String> newTagList2 = new ArrayList<>();
		newTagList2.addAll(newTagList);

		if (articleTags != null && articleTags.size() > 0) {
			for (ArticleTag at : articleTags) {
				Tag tag = new Tag();
				tag.setId(at.getTagId());
				tag = tagService.selectOne(tag);
				oldTagList.add(tag.getName());
			}
		}
		List<String> oldTagList2 = new ArrayList<>();
		oldTagList2.addAll(oldTagList);
		oldTagList.removeAll(newTagList);
		if (oldTagList.size() > 0) {
			for (String string : oldTagList) {
				Tag tag = new Tag();
				tag.setName(string);
				tag = tagService.selectOne(tag);
				ArticleTag articleTag2 = new ArticleTag(article.getId(), tag.getId());
				articleTagService.delete(articleTag2);
			}
		}
		newTagList2.removeAll(oldTagList2);
		if (newTagList2.size() > 0) {
			for (String tag : newTagList2) {
				Tag t = new Tag();
				t.setName(tag);
				Tag selectTag = tagService.selectOne(t);
				if (selectTag == null) {
					tagService.insert(t);
					selectTag = t;
				}
				articleTagService.insert(new ArticleTag(article.getId(), selectTag.getId()));
			}
		}

		return modelAndView;
	}

	@RequestMapping("/manager/article/picture")
	@ResponseBody
	public Map<String, Object> savePicture(
			@RequestParam(value = "editormd-image-file", required = true) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> map = new HashMap<>();
		System.out.println("filename::" + file.getOriginalFilename());
		String trueFileName = file.getOriginalFilename();

		String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

		String fileName = System.currentTimeMillis() + "_" + trueFileName;

		String path = request.getRealPath("/") + "assets/upload/";
		System.out.println("path::" + path);

		File targetFile = new File(path, fileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}

		// 保存
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("url", request.getContextPath() + "/assets/upload/" + fileName);
		map.put("success", 1);
		map.put("message", "upload success!");

		return map;
	}
}
